package lhc.alg.top100;

/**
 * description: https://leetcode.cn/problems/rotate-list/
 *  需要技巧 把链表闭合成环 找到新链表的最后一个节点 断开
 * author: hongchen.liao
 * date:  2022/7/31
 */
public class _61_RotateList {


    //Definition for singly-linked list.
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(k == 0 || head == null || head.next == null){
                return head;
            }
            int n = 1;
            ListNode iter = head;
            while(iter.next != null){
                iter = iter.next;
                n++;
            }
            int add = n - k % n;
            if(add == n){
                return head;
            }
            //连成一个环
            iter.next = head;
            //将iter指向新链表的最后一个位置
            while(add-- > 0){
                iter = iter.next;
            }
            ListNode ret = iter.next;
            iter.next = null;
            return ret;
        }
    }

}
